from smap.driver import SmapDriver
from smap.util import periodicSequentialCall
import calendar
from dateutil import tz
from datetime import datetime
import os

class hoboDriver(SmapDriver):
	
	def setup(self, opts):
		folder = '/home/dheinzerling/BSG/bsg on 169.229.130.74/!Projects/HVAC/UFAD/NSA - 2012 (restricted permissions)/Data/HOBO/Strings/new/'
		self.ids = {}
		self.data = {}
		self.heights = {}
		for filename in os.listdir(folder):
			f = open(folder + filename, 'rb')
			dataName = filename[:6]
			self.data[dataName] = f.readlines()[1:]
			self.heights[dataName] = self.data[dataName][0].split(',')
			#tempName = dataName + '_temp'
			#rhName = dataName + '_rh'
			if len(self.data[dataName]) > 0:
				for i in xrange(3,7):
					tempName = dataName + '_' + str(int(round(float(self.heights[dataName][i]),0))) + '_temp'
					ts = self.add_timeseries('/%s' % tempName, 'F', data_type="double")
					self.ids[tempName] = ts['uuid']
					print tempName
				#if len(self.data[dataName][10].split('\t')[3]) > 0:
				#	ts = self.add_timeseries('/%s' % rhName, '%', data_type="double")
				#	self.ids[rhName] = ts['uuid']
			else:
				print dataName
				del self.data[dataName]
			
			f.close()		
		self.period = opts.get("Period", 1000000)

	def start(self):
		periodicSequentialCall(self.read).start(self.period)
	
	def read(self):
		time_zone = tz.gettz('America/New_York')
		for dataName in self.data:
			print dataName
			errorCount = 0
			for row in self.data[dataName][2:]:
				line = row.split(',')
				try:
					point_date = datetime.strptime(line[1] + ' ' + line[2], '%m/%d/%Y %H:%M').replace(tzinfo = time_zone)
					smaptime = calendar.timegm(point_date.utctimetuple())
				except:
					#print datetime.strptime(line[1], '%m/%d/%y %H:%M:%S.0').replace(tzinfo = time_zone)
					continue
				try:
					for i in xrange(3,7):
						self.add(self.ids[dataName + '_' + str(int(round(float(self.heights[dataName][i]),0))) + '_temp'], smaptime, float(line[i]))
					#if dataName + '_rh' in self.ids:
					#	self.add(self.ids[dataName + '_rh'], smaptime, float(line[3]))
						
				except ValueError:
					errorCount += 1
			print errorCount
